<?php

namespace App\Console\Commands\Tasks\Data;
use App\Repositories\DataSummaryRepository;
use Carbon\Carbon;
use Illuminate\Console\Command;

class ComputeSummaryDailyUser extends Command
{
    //命令名
    protected $signature = 'task:compute-summary-daily-user {start_date=0} {end_date=0}';

    //命令描述
    protected $description = '计算每日用户汇总数据';

    // 业务处理
    public function handle()
    {
        $this->info("运行时间:" . date("Y-m-d H:i:s"));
        try {
            $startDate = $this->argument('start_date');
            if (empty($startDate)) {
                $startDate = Carbon::create()->subDay()->startOfDay();
                $this->info("未输入开始日期，默认为一天前:" . $startDate->toDateString());
            } else {
                if (!Carbon::hasFormat($startDate, "Ymd")) {
                    throw new \Exception("输入的开始日期不合法！");
                }
                $startDate = Carbon::createFromFormat("Ymd", $startDate)->startOfDay();
            }

            $endDate = $this->argument('end_date');
            if (empty($endDate)) {
                $endDate = Carbon::create()->subDay()->endOfDay();
                $this->info("未输入结束日期，默认为前一天:" . $endDate->toDateString());
            } else {
                if (!Carbon::hasFormat($endDate, "Ymd")) {
                    throw new \Exception("输入的结束日期不合法！");
                }
                $endDate = Carbon::createFromFormat("Ymd", $endDate)->endOfDay();
            }

            if ($startDate->greaterThan($endDate)) {
                throw new \Exception("开始时间不能大于结束时间！");
            }

            $this->deal($startDate, $endDate);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
    }

    public function deal($startObj, $endObj) {
        while ($startObj->lessThanOrEqualTo($endObj)) {
            $curObj = $startObj;
            $repo = app("repo_data_summary");

            $userReceiveList = $repo->batchGetUserReceiveGiftDaily($curObj);

            if (empty($userReceiveList) || $userReceiveList->isEmpty()) {
                $this->warn($curObj->toDateString() . "没有数据！");
            } else {
                $repo->insertUserDailyWithDate($userReceiveList, $curObj);

                $this->info($curObj->toDateString() . "的数据生成完毕！");
            }

            $startObj->addDay();
        }
    }

}